package cn.lyp.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginCheckFilter extends ZuulFilter {


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        Logger log = LoggerFactory.getLogger(LoginCheckFilter.class);

        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        log.info("请求地址",uri);
        if (uri.endsWith("/login") || uri.endsWith("/register")
         || uri.endsWith("/static/")) {
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //1.获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //响应对象
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        //2.获取请求头中的 token
        String token = request.getHeader("token");
        if (token == null||token.length()==0) {
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
            } catch (Exception e) {
                e.printStackTrace();
            }
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        return null;
    }
}
